package com.tuoren.forward.service;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.tuoren.forward.constant.CommonConstant;
import com.tuoren.forward.entity.Device;
import com.tuoren.forward.entity.User;
import com.tuoren.forward.entity.dto.DeviceDto;
import com.tuoren.forward.entity.req.DeviceAddReq;
import com.tuoren.forward.entity.req.DeviceRecordSearchReq;
import com.tuoren.forward.entity.req.DeviceSearchReq;
import com.tuoren.forward.entity.resp.DeviceResp;
import com.tuoren.forward.mapper.DeviceMapper;
import com.tuoren.forward.util.AccessTokenUtil;
import com.tuoren.forward.util.Result;
import com.tuoren.forward.util.ResultPage;
import com.tuoren.forward.util.UUIDUtil;

@Service
public class DeviceService {

	@Autowired
	DeviceMapper deviceMapper;
	
	@Autowired
    MongoTemplate mongoTemplate;
	
	/**
	 * @title 查询设备
	 * @param req
	 * @return ResultPage<Device>
	 */
	public ResultPage<DeviceResp> search(DeviceSearchReq req){
		Page<Object> page = PageHelper.startPage(req.getPage(), req.getSize());
		DeviceDto dto = new DeviceDto();
		BeanUtils.copyProperties(req, dto);
		List<DeviceResp> devices = deviceMapper.select(dto);
		return ResultPage.success(devices,page.getTotal());
	}
	
	/**
	 * @title 添加设备
	 * @param req
	 * @return Result
	 */
	public Result add(DeviceAddReq req) {
		String userId = AccessTokenUtil.getUserId();
		Date date = new Date();
		Device exist = deviceMapper.selectByMac(req.getMac());
		if(exist != null) {
			return Result.fail("设备已存在");
		}
		Device device = new Device();
		BeanUtils.copyProperties(req, device);
		device.setId(UUIDUtil.get32UUID());
		device.setTenantId(userId);
		device.setCreatetime(date);
		deviceMapper.insertSelective(device);
		return Result.success();
	}
	
	/**
	 * @title 修改设备
	 * @param req
	 * @return Result
	 */
	public Result edit(DeviceAddReq req) {
		Date date = new Date();
		Device device = new Device();
		BeanUtils.copyProperties(req, device);
		device.setModifytime(date);
		device.setMac(null);
		deviceMapper.updateByPrimaryKeySelective(device);
		return Result.success();
	}
	
	/**
	 * @title 删除设备
	 * @param req
	 * @return Result
	 */
	public Result delete(String id) {
		deviceMapper.deleteByPrimaryKey(id);
		return Result.success();
	}
	
	/**
	 * @title 查询设备记录
	 * @param req
	 * @return ResultPage<JSONObject>
	 */
	public ResultPage<JSONObject> searchRecord(DeviceRecordSearchReq req){
		User user = AccessTokenUtil.getUser();
		Query query = new Query();
		if(user.getRoleIds()==null || !user.getRoleIds().contains(CommonConstant.ROLE_MANAGER)) {
			query.addCriteria(Criteria.where("tenantId").is(user.getId()));
		}
		if(!StringUtils.isEmpty(req.getDeviceId())) {
			query.addCriteria(Criteria.where("deviceId").is(req.getDeviceId()));
		}
		if(!StringUtils.isEmpty(req.getMac())) {
			query.addCriteria(Criteria.where("deviceMac").is(req.getMac()));
		}
		if(!StringUtils.isEmpty(req.getKeyWord())) {
			query.addCriteria(new Criteria().orOperator(
					Criteria.where("deviceId").regex(req.getKeyWord())
				));
		}
		long totol = mongoTemplate.count(query, "device_record");
		query.with(Sort.by(Sort.Direction.DESC, "time"));
		int skip = (req.getPage()-1)*req.getSize();
		query.skip(skip);
		query.limit(req.getSize());
		List<JSONObject> results = mongoTemplate.find(query, JSONObject.class, "device_record");
		return ResultPage.success(results, totol);
	}
}
